<template>
  <!-- 搜索弹出框 -->
  <div class="search_popup">
    <van-search
      v-model="searchVal"
      show-action
      :placeholder="plaVal"
      @search="onSearch"
      @cancel="onCancel"
      @input="onInput"
    />

    <!-- 弹出框中的历史和热门组件 -->
    <HistoryHot
      v-if="blockShow == 1"
      :historyListData="historyListData"
      :hotKeywordListData="hotKeywordListData"
    />

    <!-- 实时搜索组件 -->
    <SearchTipsList
      :searchTipsListData="searchTipsListData"
      v-else-if="blockShow == 2"
    />
    <SearchProducts :goodsListData="goodsListData" v-else-if="blockShow == 3" />
  </div>
</template>

<script>
// 引入子组件
import HistoryHot from "@/components/HistoryHot";
import SearchTipsList from "@/components/SearchTipsList";
import SearchProducts from "@/components/SearchProducts";
// 引入发送的请求
import {
  GetSearchPopupData,
  GetSearchTipsListData,
  GetCommodityListData,
} from "@/request/api";

export default {
  data() {
    return {
      searchVal: "",
      // 搜索框默认文本
      plaVal: "",
      blockShow: 1,
      // 历史记录数组
      historyListData: [],
      // 热门搜索数组
      hotKeywordListData: [],
      // 实时搜索数组
      searchTipsListData: [],
      // 商品列表数组
      goodsListData: [],
    };
  },
  created() {
    // 请求搜索窗口数据
    GetSearchPopupData()
      .then((res) => {
        // 搜索框默认文本
        this.plaVal = res.data.defaultKeyword.keyword;
        // 历史记录数组
        this.historyListData = res.data.historyKeywordList;
        // 热门搜索数组
        this.hotKeywordListData = res.data.hotKeywordList;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    // 输入框内容变化时触发
    onInput(val) {
      // 修改blockShow的值进行组件的切换
      this.blockShow = 2;
      // 请求实时搜索功能数据
      GetSearchTipsListData({ keyword: val }).then((res) => {
        // 实时搜索数组
        this.searchTipsListData = res.data;
      });
    },

    // 确定搜索时触发
    onSearch(val) {
      // 修改blockShow的值进行组件的切换
      this.blockShow = 3;
      GetCommodityListData({ keyword: val }).then((res) => {
        console.log(res.data.data);
        this.goodsListData = res.data.data;
      });
    },

    // 点击取消按钮时触发
    onCancel() {
      // 返回上个路径
      this.$router.go(-1);
    },
  },
  components: {
    HistoryHot,
    SearchTipsList,
    SearchProducts,
  },
};
</script>
 
<style lang = "less" scoped>
.search_popup {
  width: 100%;
  height: 100%;
  background-color: #efefef;
  position: fixed;
  /* right: 0; */
  top: 0;
  z-index: 99;
}
</style>